package com.lagou;

import org.springframework.util.ReflectionUtils;
import org.springframework.web.WebApplicationInitializer;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 5. 创建MySpringServletContainerInitializer，实现ServletContainerInitializer接口，
 *    重写onstartup方法，方法中调用第4步中MyWebApplicationInitializer的onstartup方法
 * @author chengzhj
 * @data 2021/11/12 12:46 上午
 */
public class MySpringServletContainerInitializer implements ServletContainerInitializer {
    public void onStartup(Set<Class<?>> clazzSet, ServletContext ctx) throws ServletException {
        // Servlet 3.0+容器启动时将自动扫描类路径以查找实现Spring的Webapplicationinitializer接口的所有实现
        // 将其放进一个Set集合中，提供给ServletContainerInitializer中onStartup方法的第一个参数。
        // 这一步提示没怎么看懂，参考了一些百度
        List<WebApplicationInitializer> initializers = new ArrayList<WebApplicationInitializer>();
        if (clazzSet != null) {
            for (Class<?> aClass : clazzSet) {
                if (!aClass.isInterface() && !Modifier.isAbstract(aClass.getModifiers()) && WebApplicationInitializer.class.isAssignableFrom(aClass)) {
                    try {
                        initializers.add((WebApplicationInitializer) ReflectionUtils.accessibleConstructor(aClass).newInstance());
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
